﻿using CanDoo.Data;
using CanDoo.Oil.WebApi.Api.Results;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;

namespace CanDoo.Oil.WebApi.Areas.Api.Filters
{
    public class TinderValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;
            if (!modelState.IsValid)
            {
                var result = new ApiResult<ModelStateDictionary>();
                result.ResultType = ApiResultType.error;
                result.Data = modelState;
                result.Message = "输入数据验证失败";
                //找到出错的字段以及出错信息
                var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                    .Select(x => new { x.Key, x.Value.Errors });
                result.InnerMessage = string.Join(",", errorFieldsAndMsgs.SelectMany(p => p.Errors.Select(t => t.ErrorMessage)).ToArray());

                //actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, result);

                //actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, result);

                actionContext.Response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.GetEncoding("UTF-8"), "application/json")
                };
            }

        }
    }
}